package com.wang.store.service.impl;

import com.wang.store.entity.User;
import com.wang.store.mapper.UserMapper;
import com.wang.store.service.IUserService;
import com.wang.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;


/**
 * 用户模块业务层实现;
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public void reg(User user) {
        // 根据参数user对象获取注册的用户名
        String username = user.getUsername();
        // 调用持久层的User findByUsername(String username)方法，根据用户名查询用户数据
        User result = userMapper.findByUserName(username);
        // 判断查询结果是否不为null
        if (result !=null) {
            // 是：表示用户名已被占用，则抛出UsernameDuplicateException异常
            throw new UsernameDuplicateException("用户名被占用");
        }

        // 补全数据：加密后的密码
        String oldPassword = user.getPassword();
        String salt = UUID.randomUUID().toString().toUpperCase();
        String md5Password=getMD5Password(oldPassword,salt);
        user.setPassword(md5Password);

        // 补全数据：isDelete(0)
        user.setIsDelete(0);
        //补全盐值
        user.setSalt(salt);

        // 补全数据：4项日志属性
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);

        // 表示用户名没有被占用，则允许注册
        // 调用持久层Integer insert(User user)方法，执行注册并获取返回值(受影响的行数)
        Integer row = userMapper.insert(user);
        if (row!=1) {
            throw new InsertException("用户注册的时候遇到了未知错误");
        }
    }

    @Override
    public User login(String username, String password) {
        User result = userMapper.findByUserName(username);
        if (result == null) {
            throw  new UserNotFoundException("用户数据不存在");
        }
        // 判断查询结果中的isDelete是否为1
        // 是：抛出UserNotFoundException异常
       if(result.getIsDelete()==1){
           throw  new UserNotFoundException("用户没有找到");
       }
       //获取数据库加密之后的密码
        String oldPassword = result.getPassword();
        // 从查询结果中获取盐值
        String salt = result.getSalt();
        // 调用getMd5Password()方法，将参数password和salt结合起来进行加密
        String newMd5Password=getMD5Password(password,salt);
        // 判断查询结果中的密码，与以上加密得到的密码是否不一致
        if (!newMd5Password.equals(oldPassword)) {
            // 是：抛出PasswordNotMatchException异常
            throw new PasswordNotmatchException("密码没有找到");
        }

        // 将查询结果中的uid、username、avatar封装到新的user对象中
        // 返回新的user对象
        //系统调优
        User user = new User();
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setAvatar(result.getAvatar());
        return user;
    }

    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User result = userMapper.findByUid(uid);
        if (result==null||result.getIsDelete()==1) {
            throw new UserNotFoundException("用户没有找到");
        }
        //原始密码与数据库的密码进行比较
        String oldMd5Password = getMD5Password(oldPassword, result.getSalt());
        if (!oldMd5Password.equals(result.getPassword())) {
            throw new PasswordNotmatchException("密码错误");
        }
        //新密码加密
        String newMd5Password = getMD5Password(newPassword, result.getSalt());
        Integer rows = userMapper.updatePasswordByUid(uid, newMd5Password, username, new Date());
        if (rows!=1){
            throw new UpdateException("更新时产生了异常");
        }


    }

    @Override
    public User getByUid(Integer uid) {
        User result = userMapper.findByUid(uid);
        if (result==null) {
            throw new UserNotFoundException("用户数据不存在");
        }
        User user = new User();
        user.setUsername(result.getUsername());
        user.setGender(result.getGender());
        user.setEmail(result.getEmail());
        user.setPhone(result.getPhone());
        return user;
    }


    @Override
    public void ChangeInfo(Integer uid, String username, User user) {
        User result = userMapper.findByUid(uid);
        if (result==null) {
            throw new UserNotFoundException("用户数据不存在");
        }
       user.setUid(uid);
       // user.setUsername(username);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());
        Integer info = userMapper.UpdateInfoByUid(user);
        if (info==null) {
            throw  new UpdateException("更新数据时出现了异常");
        }

    }

    @Override
    public void ChangeAvatar(Integer uid, String avatar, String username) {
        //查询当前数据是否存在
        User result = userMapper.findByUid(uid);
        if (result==null ||result.getIsDelete()==1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        Integer rows = userMapper.UpdateAvatarByUid(uid, avatar, username, new Date());
        if (rows!=1){
            throw  new UpdateException("更新头像出现1异常");
        }
    }

    /**
     * 执行密码加密
     * @param password 原始密码
     * @param salt 盐值
     * @return 加密后的密文
     */
    public String getMD5Password(String password,String salt){
        //md5方法的调用(进行三次加密)
        for (int i = 0; i < 3; i++) {
         password = DigestUtils.md5DigestAsHex((salt+password+salt).getBytes()).toUpperCase();
        }
        return password;
    }
}
